package com.yhl.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhl.admin.bean.User;
import com.yhl.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author yhl
 * @create 2021-06-18 16:37
 */
@Controller
public class TableController {

    private static final int SIZE = 2;//每页显示条数

    @Autowired
    UserService userService;


//    @GetMapping("/basic_table")
//    public String basic_table(Model model){
//
//        int i = 10 /0;
//
//        List<User> users = Arrays.asList(new User("xiaohua", "1234"),
//                new User("xiaohua", "1234"),
//                new User("xiaohua", "1234"),
//                new User("xiaohua", "1234"),
//                new User("xiaohua", "1234"));
//
//        model.addAttribute("users", users);
//
//        return "/tables/basic_table";
//    }

    //添加用户
    @GetMapping("/addUser")
    public String addUser(User user,
                          @RequestParam(value = "pn",defaultValue = "1")int pn,
                          RedirectAttributes ra){

        userService.save(user);
        ra.addAttribute("pn", pn);

        return "redirect:/dynamic_table";
    }

    @GetMapping("/delete/by/{id}")
    public String delete(@PathVariable("id") int id,
                         @RequestParam(value = "pn", defaultValue = "1")int pn,
                         RedirectAttributes ra){

        userService.removeById(id);
        ra.addAttribute("pn", pn);
        return "redirect:/dynamic_table";
    }

    @GetMapping("/dynamic_table")
    public String dynamic_table(@RequestParam(value = "pn", defaultValue = "1")Integer pn,
                                Model model){

        //page – 翻页对象
        //queryWrapper – 实体对象封装操作类
        Page<User> userPage = new Page<>(pn, SIZE);

        Page<User> page = userService.page(userPage);
        page.getCurrent();
        page.getTotal();
        page.getPages();


        //将page对象保存到model中
        model.addAttribute("page", page);


        return "/tables/dynamic_table";
    }

    @GetMapping("/responsive_table")
    public String responsive_table(){
        return "/tables/responsive_table";
    }

    @GetMapping("/editable_table")
    public String editable_table(){
        return "/tables/editable_table";
    }
}
